package cn.crex1.xiaomi.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TimeUtil<E> {

	private static Logger logger = LoggerFactory.getLogger(TimeUtil.class);

	private static Timer timer = new Timer();

	private static List timelist = new ArrayList<>(4);

	private static Boolean flag = false;

	private static Integer startcout = 0;

	private static List cachelist = new ArrayList<>();

	@SuppressWarnings("unchecked")
	public static <E> List<E> timerLists(List<E> targetList,int interval) {
		if (flag) {
			cachelist = targetList;
			timer.schedule(new TimerTask() {
				@Override
				public void run() {
					logger.debug("ScheduledExecutorService-----------timerLists:start");
					if (targetList.size() % 4 == 0) {
						timelist = addElement(cachelist, 0,interval);
					} else {
						int size = cachelist.size() - (cachelist.size() % 4);
						timelist = addElement(cachelist, size,interval);
					}
				}
			},180000);
		} else {
			if (targetList.size() % 4 == 0) {
				timelist = addElement(targetList, 0,interval);
			} else {
				int size = targetList.size() - (targetList.size() % 4);
				timelist = addElement(targetList, size,interval);
			}
			flag = true;
		}
		return timelist;
	}

	public static <E> List<E> addElement(List<E> targetList, int size,int interval) {
		List<E> timelist = new ArrayList<>(interval);
		if (size == 0) {
			for (int j = 0; j < interval; j++) {
				timelist.add(j, targetList.get(j + startcout));
				if (j == (interval-1)) {
					startcout = j + startcout + 1;
				}
			}
			if (startcout + interval == targetList.size()) {
				startcout = 0;
			}
		} else {
			if (startcout + interval != size) {
				for (int j = 0; j < interval; j++) {
					timelist.add(j, targetList.get(j + startcout));
					if (j == (interval-1)) {
						startcout = j + startcout + 1;
					}
				}
				if (startcout + interval + (targetList.size() % interval) == targetList.size()) {
					startcout = 0;
				}
			}
		}
		return timelist;
	}
}
